//
//  XYTabBarItem.swift
//  SinaWB_XY
//
//  Created by 小熊猫 on 15/10/17.
//  Copyright © 2015年 小熊猫. All rights reserved.
//

import UIKit

class XYTabBarItem: UITabBarItem {

    override var badgeValue: String? {
        didSet{
            setBadgeNewValue()
        }
    }
    
    private func setBadgeNewValue(){
        
        //取得父控制器
        let taget = self.valueForKeyPath("_target") as! UITabBarController
        
        //从控制器中遍历出tabbarButton
        for tabBarSub in taget.tabBar.subviews{
            if tabBarSub.isKindOfClass(NSClassFromString("UITabBarButton")!){
                //从tabbarButton中遍历出承载控件的view
                for tabBarButtonSub in tabBarSub.subviews{
                    if tabBarButtonSub.isKindOfClass(NSClassFromString("_UIBadgeView")!){
                        //从view上便利出承载图片的控件
                        for badgeViewSub in tabBarButtonSub.subviews{
                            if badgeViewSub.isKindOfClass(NSClassFromString("_UIBadgeBackground")!){
                                
                                //抽取这个控件身上的成员变量
                                var count:UInt32 = 0
                                let ivas = class_copyIvarList(NSClassFromString("_UIBadgeBackground"), &count)
                                for i in 0..<count{
                                    let ivar = ivas[Int(i)]
                                    let ivarName = NSString(CString: ivar_getName(ivar), encoding: NSUTF8StringEncoding)
//                                    printLog(ivarName)
                                    //如果是图片的属性,就利用运行时赋值
                                    if ivarName!.isEqualToString("_image"){
                                        //注意! ivarName 需要转换成string类型
                                        //注意2! 给谁赋值.谁调用
                                        badgeViewSub.setValue(UIImage(named: "main_badge"), forKeyPath: (ivarName as! String))
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
}
